<template>
  <div class="login">
    <van-nav-bar class="top">
      <template #title>
        <h4>登录</h4>
      </template>
    </van-nav-bar>

    <van-form ref="form" class="form" @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="mobile"
      />
      <van-field
        v-model="form.sms"
        center
        clearable
        label="短信验证码"
        placeholder="请输入短信验证码"
        :rules="code"
      >
        <template #button>
          <van-button
            size="small"
            @click.prevent="send"
            type="primary"
            class="code"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button round block type="info" native-type="submit"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { codeApi, loginApi, userInfoApi } from '@/api/loginApi.js'
import { localSet } from '@/utils/mylocal.js'
import { mapMutations } from 'vuex'
export default {
  data () {
    return {
      form: {
        mobile: '13911112222',
        sms: '246810'
      },
      mobile: [
        { required: true, message: '手机号不能为空', trigger: 'onBlur' },
        {
          validator (val) {
            // 验证手机号
            return /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/.test(
              val
            )
          },
          message: '请输入合法的手机号'
        }
      ],
      code: [{ required: true, message: '验证码不能为空', trigger: 'onBlur' }]
    }
  },
  methods: {
    ...mapMutations(['getUserInfo']),
    async send () {
      console.log('我在发送验证码', this.form.mobile)
      const res = await codeApi(this.form.mobile)
      console.log(res.message === 'OK')
      if (res.message === 'OK') {
        this.form.sms = '246810'
      }
      // }
    },
    async onSubmit () {
      this.$toast.loading('登录中...')
      console.log('我在提交', this.form.mobile, this.form.sms)
      const res = await loginApi(this.form.mobile, this.form.sms)
      if (res.message === 'OK') {
        localSet('token', res.data)
        userInfoApi().then(res => {
          if (res.message === 'OK') {
            this.getUserInfo(res.data)
          }
        })
        this.$toast.success('登录成功')
        setTimeout(() => {
          this.$router.push('/index')
        }, 1000)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.top {
  background: #3296fa;
  h4 {
    color: white;
    font-size: 20px;
  }
}

.code {
  background: #3296fa;
}

footer {
  padding: 0 10px;
  .btn {
    background: #3296fa;
    border-radius: 8px;
    color: white;
  }
}
</style>
